import FileSaver from "file-saver";
export default class Ut {
  // 图片加载错误方法
  // static errorImg(event, img1) {
  //   let img = event.srcElement ? event.srcElement : event.target;
  //   img.src = img1 || require("../img/ApplyManager/error_pic.png");
  //   img.οnerrοr = null;
  // }

  /**
   * @author 张维金
   * @date 2024-02-20 星期二
   * @function 休眠一定时间
   * @param {Number} time
   * @return {Promise}
   */
  static sleep(time) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, time);
    });
  }
  /**
   * 保存数据到本地
   * @param {Object} options
   */
  static saveFileToLocal(options) {
    let { content, type, name } = options;
    type = type || "text/plain;charset=utf-8";
    FileSaver.saveAs(new Blob([content], { type }), name);
  }

  /**
   * 获取当前时间戳后几位
   * @param {Number} n
   */
  static getDateNum(n) {
    return (Date.now() + "").slice(-(n || 2));
  }
  /**
   * 根据对象中元素去重
   * @param {Array} arr
   * @param {String} name
   */
  static arrayUnique(arr, name) {
    var hash = {};
    return arr.reduce((item, next) => {
      hash[next[name]] ? "" : (hash[next[name]] = true && item.push(next));
      return item;
    }, []);
  }

  /**
   * 设置本地存储
   * @param {String} name
   * @param {*} str
   */
  static setLocal(name, str) {
    localStorage.setItem(name, typeof str == "object" ? JSON.stringify(str) : str.toString());
  }
  /**
   * 获取本地存储
   * @param {String} name
   */
  static getLocal(name, def) {
    let str = localStorage.getItem(name) || def;
    try {
      if (!isNaN(str)) return str;
      return JSON.parse(str);
    } catch (e) {
      return str;
    }
  }
  /**
   * 获取rgba中的数值
   * @param {String} str
   */
  static getRgbaNumber(str) {
    let arr = (str || "").match(/(\d+), (\d+), (\d+), (.+)\)/) || [0, 255, 255, 255, 1];
    return [arr[1], arr[2], arr[3], arr[4] * 255];
  }
  /**
   * 获取rgba中的数值
   * @param {Object} obj 对象转字符串
   */
  static getRgbaNumber2(obj) {
    let { red, green, blue, alpha } = obj;
    alpha = ((alpha || 255) / 255).toFixed(2);
    return `rgba(${red}, ${green || 255}, ${blue || 255},${alpha})`;
  }
  /**
   * 获取rgba中的数值
   * @param {String} str 透明度为255
   */
  static getRgbaNumber3(str) {
    let arr = (str || "").replace(/\s/g, "").match(/(\d+),(\d+),(\d+),(.+)\)/) || [0, 255, 255, 255, 1];
    return [parseInt(arr[1]), parseInt(arr[2]), parseInt(arr[3]), parseInt(arr[4] * 255)];
  }
  /**
   * 为数据url加上鉴权token
   * @param {String} url
   * @param {String} token
   */
  static addToken(url, token) {
    let isParam = /\?/.test(url);
    let isToken = /token=/.test(url);
    if (isToken) {
      url = url.replace(/token=/, `token=${token}`);
    } else {
      url = url + `${isParam ? "&" : "?"}token=${token}`;
    }
    return url;
  }

  /**
   * 生成guid
   */
  static createGuid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
      let r = (Math.random() * 16) | 0;
      let v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

  static requestXHR(option) {
    if (String(option) !== "[object Object]") return undefined;
    option.method = option.method ? option.method.toUpperCase() : "GET";
    option.data = option.data || {};
    let formData = [];
    for (let key in option.data) {
      formData.push("".concat(key, "=", option.data[key]));
    }
    option.data = formData.join("&");

    if (option.method === "GET") {
      option.url += location.search.length === 0 ? "".concat("?", option.data) : "".concat("&", option.data);
    }

    let xhr = new XMLHttpRequest();
    xhr.responseType = option.responseType || "json";
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          if (option.success && typeof option.success === "function") {
            option.success(xhr.response);
          }
        } else {
          if (option.error && typeof option.error === "function") {
            option.error();
          }
        }
      }
    };
    xhr.open(option.method, option.url, true);
    if (option.method === "POST") {
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }
    xhr.send(option.method === "POST" ? option.data : null);
  }

  /**
   * 原生异步获取接口数据封装
   * @param {Object} option
   */
  static request(option) {
    return new Promise((success, error) => {
      Ut.requestXHR({ ...option, ...{ success, error } });
    });
  }
}
